<?php

namespace app\admin\model;

use think\Db;
use think\Model;
use traits\model\SoftDelete;

class Products extends Model
{

    use SoftDelete;

    const MARKETABLE_UP = 1; //上架
    const MARKETABLE_DOWN = 1; //下架
    const DEFALUT_NO = 0; //非默认货品
    const DEFALUT_YES = 1; //默认货品

    // 表名
    protected $name = 'products';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [

    ];


    /**
     * 保存货品
     * User:wjima
     * Email:1457529125@qq.com
     * @param array $data
     * @return int|string
     * @throws \think\Exception
     */
    public function doAdd($data = [])
    {
        $stock = isset($data['stock']) ? $data['stock'] : 0;
        unset($data['stock']);

        $data['createtime'] = time();
        $data['updatetime'] = time();

        $product_id = $this->allowField(true)->insertGetId($data);

        $where['id'] = ['=', $product_id];
        if ($stock != 0) { //增加库存
            $exp     = Db::raw('cast(stock as signed) + ' . $stock . '>= 0');
            $where[''] = ['exp', $exp];
            $this->where($where)->setInc('stock', $stock);
        }

        return $product_id ? $product_id : 0;
    }


    //后台是实际库存，实际库存变动时，需要加上冻结库存
    public function updateProduct($product_id, $data = [])
    {
        $stock = isset($data['stock']) ? $data['stock'] : 0;
        unset($data['stock']);
        $res     = $this->allowField(true)->update($data, ['id' => $product_id]);
        $where['id'] = ['=', $product_id];
        if ($stock != 0) {
            //$this->where($where)->setInc('stock', $stock);
            $exp     = Db::raw('cast(stock as signed) + ' . $stock . '>= 0');
            $where[''] = ['exp', $exp];
            $re      = $this->where($where)->setInc('stock', $stock);
            if (!$re) {
                $res = false;
            }
        }
        return $res;
    }

    public function deleteProduct($ids = [])
    {
        return $this->where('id', 'in', $ids)->delete(true);
    }



}
